#ifndef _FORWARD_LIST_INCLUDED_
#define _FORWARD_LIST_INCLUDED_
#include <unordered_map>
#include "core/reactor/connection.h"
#include <time.h>
#include <sys/time.h>
//#include <stdio.h>
typedef std::string fid_t;

//转发表类，用于存储用户连接和转发ID
class forwardList
{
private:
    std::map<connection_t*, fid_t> userList;
    std::map<fid_t, connection_t*> _forwardList;
    
public:
    forwardList() = default;
    ~forwardList() = default;

    //将用户连接插入转发表
    fid_t insertUser(connection_t* conn)
    {
        if(conn == nullptr) return fid_t();
        if(userList.find(conn) == userList.end()){
            fid_t id = getNewId();
            userList[conn] = id;
            _forwardList[id] = conn;
        }
        return userList[conn];
    }

    //通过用户连接获取对应forward_id
    fid_t getForwardId(connection_t* conn)
    {
        if(conn == nullptr) return fid_t();
        if(userList.find(conn) == userList.end()){ 
            return fid_t();
        }else{
            return userList[conn];
        }
        
    }

    //通过forward_id获取用户连接
    connection_t* getUserConn(fid_t forwardId)
    {
        if(forwardId.size() == 0) return nullptr;
        if(_forwardList.find(forwardId) == _forwardList.end()){
            return nullptr;
        }else{
            return _forwardList[forwardId];
        }

    }

    //从转发表中将用户移除
    void removeUser(connection_t* conn)
    {
        if(conn == nullptr) return;
        fid_t temp =  getForwardId(conn);
        if(temp.empty()) return;
        userList.erase(conn);
        _forwardList.erase(temp);
    }

    void removeUser(fid_t forwardId)
    {
        if(forwardId.empty()) return;
        connection_t* temp = getUserConn(forwardId);
        if(temp == nullptr) return;
        userList.erase(temp);
        _forwardList.erase(forwardId);
    }

    //forward_id获取函数，使用微秒级时间戳作为forward_id
    fid_t getNewId(){
        struct timeval tv;
        gettimeofday(&tv,NULL);
        struct tm* pTime;
        pTime = localtime(&tv.tv_sec);
            
       /* char sTemp[30] = {0};
        snprintf(sTemp, sizeof(sTemp), "%04d%02d%02d%02d%02d%02d%03d%03d", pTime->tm_year+1900, \
                pTime->tm_mon+1, pTime->tm_mday, pTime->tm_hour, pTime->tm_min, pTime->tm_sec, \
                tv.tv_usec/1000,tv.tv_usec%1000);*/
        string temp;
        #define tos std::to_string 
        temp = tos(pTime->tm_year+1900)+tos(pTime->tm_mon+1)+tos(pTime->tm_mday)+tos(pTime->tm_hour)+tos( pTime->tm_min)\
        +tos(pTime->tm_sec)+tos(tv.tv_usec/1000)+tos(tv.tv_usec%1000);
        return (fid_t)temp;
    }
};



#endif